package com.nlx.notes.support.helper.login;

import cn.hutool.core.util.StrUtil;
import com.nlx.notes.module.bean.vo.login.UserTokenVO;
import com.nlx.notes.module.core.consts.RedisConst;
import com.nlx.notes.module.core.util.JSONUtils;
import com.nlx.notes.module.core.util.UUIDUtils;
import com.nlx.notes.module.entity.Users;
import com.nlx.notes.support.helper.redis.RedisHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class TokenStoreHelper {

    final RedisHelper redisHelper;

    public TokenStoreHelper(RedisHelper redisHelper) {
        this.redisHelper = redisHelper;
    }

    public UserTokenVO storeToken(Users user) {
        log.info(" store user token ,user -> {}", JSONUtils.toString(user));
        UserTokenVO userTokenVO = new UserTokenVO();

        String accessToken = UUIDUtils.genUUId();
        String refreshToken = UUIDUtils.genUUId();
        //存储access token
        redisHelper.setValue(accessToken,user, RedisConst.Token.USER_LOGIN_TOKEN_TIMOUT_LIMIT,
                RedisConst.Token.USER_LOGIN_TOKEN_TIMOUT_LIMIT_unit);
        userTokenVO.setAccessToken(accessToken);
        userTokenVO.setRefreshToken(refreshToken);
        userTokenVO.setUserCode(user.getUserCode());
        userTokenVO.setUserType(user.getUserType());
        userTokenVO.setExpiresIn(RedisConst.Token.USER_LOGIN_TOKEN_TIMOUT_LIMIT);
        return userTokenVO;
    }

    public boolean cleanUserToken(String accessToken){
        if(StrUtil.isEmpty(accessToken)){
            return  false;
        }
        return redisHelper.removeKey(accessToken);
    }
}
